package com.example.hospitalmanagementapp

import Request.SaltRequest
import android.app.Application
import android.util.Log
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory

class BaseApplication:Application() {
    companion object{
        lateinit var saltRequest: SaltRequest

    }
    override fun onCreate() {
        super.onCreate()
        // 构建Retrofit
        val retrofit= Retrofit.Builder()
            .baseUrl("http://192.168.31.110:8080/")
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .client(OkHttpClient.Builder()
                .addInterceptor {
                    var request=it.request()
                    var response=it.proceed(request)
                    var httpCode =response.code()
                    var msg=response.message()
                    var result=response.body()?.string()
                    var meidiaType=response.body()?.contentType()
                    result=parseResponse(result!!)
                    Log.d("Okttp","$httpCode$msg")
                    Log.d("Okttp","$result")
                    response.newBuilder().body(ResponseBody.create(meidiaType,result)).build()

                }.build())
            .build()
        // 实例化接口
        saltRequest=retrofit.create(SaltRequest::class.java)
                }


    private fun parseResponse(json: String): String {
        var jsonObjects= JSONObject(json)
        if (jsonObjects.has("code")){
            var errorCode=jsonObjects.getInt("code")
            if (errorCode==200){
                var result=jsonObjects.getJSONObject("message")
                return result.toString()
            }
        }
        return ""

    }

}